package LeetCode._01_树;
/**
 * https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 * 
 */
public class _105_从前序与中序遍历序列构造二叉树 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder,0, preorder.length-1,
                inorder,0,inorder.length-1);
    }

    //找到根节点，前序遍历找到根节点，然后去中序遍历找到根节点的索引，判断索引，然后递归创建根节点
    private TreeNode build(int[] preorder,int preStart,int preEnd,
                           int[] inorder,int inStart,int inEnd){
        if(preStart>preEnd || inStart>inEnd) return null;
        int rootVal = preorder[preStart]; //根节点在前序遍历的第一个位置
        int index = -1;
        for(int i=inStart;i<=inEnd;++i){
            if(rootVal == inorder[i]){
                index = i; //记录根节点在二叉树的索引
                break;
            }
        }

        int leftSize = index - inStart; //记录左子树的数量

        TreeNode root = new TreeNode(rootVal);
        root.left = build(preorder,preStart+1,preStart+leftSize,
                          inorder,inStart,index-1);
        root.right = build(preorder,preStart+leftSize+1,preEnd,
                           inorder,index+1,inEnd);

        return root;
    }
}
